﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Otgruzka.Export;
using System.Threading;

namespace Otgruzka
{
    public class ExcelReport : IHttpHandler
    {
        static private HttpContext Context
        {
            get { return HttpContext.Current; }
        }
        static private HttpRequest Request
        {
            get { return Context.Request; }
        }
        static private HttpResponse Response
        {
            get { return Context.Response; }
        }

        public void ProcessRequest(HttpContext context)
        {
            testParameters();
            sendResponse();
            clearFiles();
        }

        static private void testParameters()
        {
            if (string.IsNullOrEmpty(Request["ReportID"]) || string.IsNullOrEmpty(Request["FileName"]))
                throw new Exception("Неверные параметры отчета");
        }
        static private void sendResponse()
        {
            Response.Clear();
            Response.StatusCode = 200;
            Response.ContentType = "application/msexcel";
            Response.AddHeader("content-disposition", string.Format("attachment; filename=\"{0}\"", string.Format("{0}.xls", getFileName())));
            ExcelLoader.WriteFile(Context, Request["ReportID"]);
            Response.End();
        }
        static private void clearFiles()
        {
            new Thread(ExcelLoader.RemoveOldFiles).Start();
        }
        static private string getFileName()
        {
            return Context.Server.UrlEncode(Request["FileName"]);
        }

        public bool IsReusable
        {
            get { return true; }
        }
    }
}